package tech.yozo.bamboo.model;

import android.graphics.RectF;

import java.util.Arrays;

/**
 * 待选文本
 */
public class OcrText {
    /**
     * 文本
     */
    public String[] mTexts;

    /**
     * 文本框
     */
    public int[][] mBoxes;

    /**
     * 识别置信度
     */
    public float[] mRecScores;

    /**
     * 方向分类置信度
     */
    public float[] mClsScores;

    /**
     * 方向标签，目前只支持0、180（因为PaddleOCR）
     */
    public int[] mClsLabels;

    public OcrText up;
    public OcrText down;
    public OcrText left;
    public OcrText right;

    public int marginUp;
    public int marginDown;
    public int marginLeft;
    public int marginRight;

    /**
     * 根据坐标选择文本
     * @param point 坐标
     * @return 文本
     */
    public SelectedText selectText(float[] point) {
        SelectedText text = new SelectedText();
        for (int i = 0; i < mBoxes.length; i++) {
            int[] box = mBoxes[i];
            if (point[0] > box[0] && point[0] < box[2] && point[1] > box[1] && point[1] < box[5]) {
                text.text = mTexts[i];
                text.rect = new RectF(box[0], box[1], box[4], box[5]);
                return text;
            }
        }
        return text;
    }

    /**
     * TODO 根据句式聚合OCR结果，在平面二维坐标系中聚合相近的结果作为一组
     * 这需要先后先实现一个二维排序算法，关键是确定Y激变阈值。先按X升序从前向后排，再按Y降序从后向前排
     */
    private void clusterResult() {
        int length = mBoxes.length;
        Sort[] sorts = new Sort[length];
        for (int i = 0; i < length; i++) {
            int[] box = mBoxes[i];
            int centerX = (box[2] - box[0]) / 2 + box[0];
            int centerY = (box[5] - box[1]) / 2 + box[1];
            sorts[i] = new Sort(centerX, centerY, i);
        }

        // 先按Y排序
        Arrays.sort(sorts);
        // Y激变拆分

    }

    public static class Sort implements Comparable<Sort> {
        public int centerX;
        public int centerY;
        public int index;

        public Sort(int centerX, int centerY, int index) {
            this.centerX = centerX;
            this.centerY = centerY;
            this.index = index;
        }

        @Override
        public int compareTo(Sort o) {
            return Integer.compare(this.centerY, o.centerY);
        }
    }
}
